package com.enterprise.support.filter;

import com.enterprise.support.utility.UserUtility;
import com.enterprise.support.utility.Validation;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Zhanggaojiang
 * User: Administrator
 * Date: 2010-7-13
 * Time: 9:15:51
 * 是否登录访问 控制 Filter
 */
public class LoginFilter implements Filter {
    private String KEY_NOT_LOGIN_PAGE = "/admin/logic.jsp";

    public void init(FilterConfig filterConfig) throws ServletException {
        if (!Validation.isEmpty(filterConfig.getInitParameter("KEY_NOT_LOGIN_PAGE"))) {
            KEY_NOT_LOGIN_PAGE = filterConfig.getInitParameter("KEY_NOT_LOGIN_PAGE");
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String contextPath = request.getContextPath();
        String url = request.getRequestURI().substring(contextPath.length());
        if (UserUtility.isLoginAdmin(request) || KEY_NOT_LOGIN_PAGE.matches(url)) {
            filterChain.doFilter(request, servletResponse);
        } else {
            //KEY_NOT_LOGIN_PAGE
            response.sendRedirect(KEY_NOT_LOGIN_PAGE);
        }
    }

    public void destroy() {
    }
}
